package com.yzt.zhuju.jpushreceiver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.yzt.zhuju.R;

/**
 * 前台服务  保证安卓9.0 息屏后的音视频采集
 */
public class NotificationService extends Service {

    private NotificationManager notificationManager;

    private Notification notification;

    private static final String notificationId = "channelId";

    private static final String notificationName = "channelName";

    private static final int notifyId = 1;

    /**
     * 启动前台服务
     */
    public static void startSelf(Context context) {
        Intent intent = new Intent(context, NotificationService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        setForegroundNotification();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void setForegroundNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, NotificationService.class), 0);

            NotificationChannel channel = new NotificationChannel(notificationId, notificationName, NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);

            //设置通知面板中显示的视图的信息
            notification = new Notification.Builder(this, notificationId)
                  //  .setSmallIcon(R.mipmap.icon_logo)
                    .setTicker("正在通话")
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("正在通话中")
                    .setContentIntent(pendingIntent)
                    .setPriority(Notification.PRIORITY_HIGH)
                    .build();

            //发送通知
//        notificationManager.notify(NOTIFICATION, notification);
            startForeground(notifyId, notification);
        }
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        super.onDestroy();
        if (notificationManager != null) {
            notificationManager = null;
        }
        if (notification != null)
            notification = null;
    }
}